package me.magicall.db.springjdbc;

import java.lang.reflect.InvocationTargetException;

import me.magicall.db.meta.TableMeta;
import me.magicall.db.meta.TableMetaAccessor;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;

public class UsingModelClassDao<T> extends UsingTableMetaDao<T> {

	private final Class<T> modelClass;

	public UsingModelClassDao(final TableMeta tableMeta, final NamedParameterJdbcOperations jdbc, final TableMetaAccessor tableMetaAccessor,
			final Class<T> modelClass) {
		super(tableMeta, jdbc, tableMetaAccessor);
		this.modelClass = modelClass;
	}

	public Class<T> getModelClass() {
		return modelClass;
	}

	@Override
	protected Object getProperty(final T model, final String fieldName) {
		try {
			return PropertyUtils.getProperty(model, fieldName);
		} catch (final IllegalAccessException e) {
			e.printStackTrace();
		} catch (final InvocationTargetException e) {
			e.printStackTrace();
		} catch (final NoSuchMethodException e) {//some field in db not in bean
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void setProperty(final T model, final String fieldName, final Object value) {
		try {
			PropertyUtils.setProperty(model, fieldName, value);
		} catch (final IllegalAccessException e) {
			e.printStackTrace();
		} catch (final InvocationTargetException e) {
			e.printStackTrace();
		} catch (final NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected T newT() {
		try {
			return modelClass.newInstance();
		} catch (final InstantiationException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);//impossible?
		} catch (final IllegalAccessException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);//impossible?
		}
	}
}
